package com.anjubao.parking.municipal.user.service;
import com.anjubao.parking.municipal.common.utils.U;
import com.anjubao.parking.municipal.user.dto.UserVehicleDto;
import com.anjubao.parking.municipal.user.mapper.UserVehicleMapper;
import com.anjubao.parking.municipal.user.model.UserVehicle;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import java.time.LocalDateTime;

import cn.hutool.core.collection.CollectionUtil;
import com.anjubao.parking.municipal.common.dto.ApiResult;
import com.anjubao.parking.municipal.common.exception.ServiceException;
import com.anjubao.parking.municipal.roadside.dto.UserOweFeeDto;
import com.anjubao.parking.municipal.user.dto.UserInfoMgmtDto;
import com.anjubao.parking.municipal.user.feign.RoadSideAjbFeignClient;
import com.anjubao.parking.municipal.user.form.UserQueryForm;
import com.anjubao.parking.municipal.user.mapper.UserInfoMapper;
import com.anjubao.parking.municipal.user.model.UserInfo;
import com.anjubao.parking.municipal.user.utils.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhuchunfeng
 * @date 2019/7/22 17:17
 */
@Service
@Slf4j
public class ParkingUserMgmtService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RoadSideAjbFeignClient roadSideAjbFeignClient;
    @Resource
    private UserVehicleMapper userVehicleMapper;

    public IPage<UserInfoMgmtDto> listUser(UserQueryForm form) {

        IPage<UserInfo> userInfoIPage = userInfoMapper.selectPage(
                new Page<>(form.getPage(),form.getPageSize()),
                form
        );
        log.info("查询用户信息列表 return {}",U.json(userInfoIPage));

        List<UserInfo> records = userInfoIPage.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            //所有用户code
            List<String> userCodes = records.stream().map(t -> IdUtil.getCode(t.getId())).collect(Collectors.toList());

            log.info("调用路边停车获取欠费记录 userCodes {}", U.json(userCodes));
            //获取用户欠费记录
            ApiResult<List<UserOweFeeDto>> userOweFee = roadSideAjbFeignClient.getUserOweFee(userCodes);
            log.info("调用路边停车获取欠费记录 return {}", U.json(userOweFee));
            if (userOweFee.getCode() == 5000) {
                throw new ServiceException(userOweFee.getDesc());
            }
            final Map<String, Integer> idMapOwnFee = userOweFee.getResult().stream().collect(Collectors.toMap(UserOweFeeDto::getUserCode, UserOweFeeDto::getOweFee, (t1, t2) -> t1));

            //获取用户车牌信息
            final Map<String, List<UserVehicleDto>> userVehicleBatch = getUserVehicleBatch(userCodes);

            //数据处理
            return userInfoIPage.convert(t -> {
                UserInfoMgmtDto userInfoMgmtDto = new UserInfoMgmtDto();
                userInfoMgmtDto.setUserCode(IdUtil.getCode(t.getId()));
                userInfoMgmtDto.setPhone(t.getPhone());
                userInfoMgmtDto.setName(t.getName());
                userInfoMgmtDto.setBalance(t.getBalance());
                userInfoMgmtDto.setWxNickname(t.getWxNickname());
                Integer ownFee = idMapOwnFee.get(IdUtil.getCode(t.getId()));
                userInfoMgmtDto.setOweFee(ownFee ==null?0: ownFee);
                List<UserVehicleDto> userVehicleDtoList = userVehicleBatch.get(IdUtil.getCode(t.getId()));
                userInfoMgmtDto.setVehicles(CollectionUtil.isEmpty(userVehicleDtoList)?new ArrayList<>():userVehicleDtoList);
                userInfoMgmtDto.setCreateTime(t.getCreateTime());
                return userInfoMgmtDto;
            });

        }
        return userInfoIPage.convert(t -> new UserInfoMgmtDto());
    }

    private Map<String, List<UserVehicleDto>> getUserVehicleBatch(List<String> userCodes) {
        if (CollectionUtils.isEmpty(userCodes)) {
            return new HashMap<>();
        }
        List<Long> userIds = userCodes.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserVehicle> userVehicles = userVehicleMapper.selectList(new QueryWrapper<>(new UserVehicle()).lambda().in(UserVehicle::getUserId, userIds));
        List<UserVehicleDto> collect = userVehicles.stream().map(
                t -> {
                    UserVehicleDto userVehicleDto = new UserVehicleDto();
                    userVehicleDto.setUserCode(IdUtil.getCode(t.getUserId()));
                    userVehicleDto.setVehicle(t.getVehicle());
                    userVehicleDto.setVehicleType(t.getVehicleType());
                    return userVehicleDto;
                }).collect(Collectors.toList());

        return collect.stream().collect(Collectors.groupingBy(UserVehicleDto::getUserCode));

    }
}
